package sindconsole.misc.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import sindconsole.ApplicationContextHolder;
import sindconsole.misc.bean.DictItem;
import sindconsole.misc.service.DictService;

import java.util.Arrays;
import java.util.List;

public class DictConverter implements Converter<Long> {

    public static final String DELIMITER = "/";

    DictService dictService;

    public DictConverter() {
        dictService = ApplicationContextHolder.getBean(DictService.class);
    }

    @Override
    public Class<Long> supportJavaTypeKey() {
        return Long.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        String stringValue = cellData.getStringValue();
        if(!StringUtils.hasText(stringValue)) return null;
        DictItem item = dictService.searchDictItemByPath(Arrays.asList(StringUtils.delimitedListToStringArray(stringValue, DELIMITER)));
        return item != null ? item.getId() : null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if(value == null) return new WriteCellData<>("");
        List<String> path = dictService.searchPathByDictItemId(value);
        String stringValue = !CollectionUtils.isEmpty(path) ? StringUtils.collectionToDelimitedString(path, DELIMITER) : "";
        return new WriteCellData<>(stringValue);
    }

}
